<template>
  <div>
    <TopFilter :labelWidth="110" :list="topFilterList" :cols="3" :rows="2" :collapse="false" @filterChange="handleFilterChange" />
    <!-- :fetchapi="fetchapi" -->
    <!-- :maxHeight="isFullScreen ? (isMiniScreen ? 340 : 520) : isMiniScreen ? 190 : 210" -->
    <FilterTable
      ref="topTable"
      columnsRef="partPartPurchasePurchaseOrderCreateBatchPartSelect"
      :columns="tableColumns1"
      height="auto"
      :maxHeight="isFullScreen ? tableMaxHeiht : isMiniScreen ? 190 : 210"
      :dataSource="dataSource"
      selectionType="single"
      :isMemoryPagination="true"
      :params="fetchParams"
      :onColumnsChange="columns => (this.tableColumns1 = columns)"
      :onEnterEvent="handlePartEnterEvent"
      :onRowSelectChange="handleTableSelect"
      :onSyncTableData="handleTableDataChange"
    >
      <template slot="controls">
        <el-button type="text" disabled>计划数量不为0的配件：{{ noCountPart }}</el-button>
        <el-button size="small" type="primary" @click="hadnleHighStock">按高储生成</el-button>
        <el-button size="small" type="primary" @click="handleLowStock">按低储生成</el-button>
      </template>
    </FilterTable>
    <!-- 类型选择 -->
    <el-radio-group v-model="yearFilterType" style="margin-bottom: 10px;">
      <el-radio label="1">上年同期比</el-radio>
      <el-radio label="2">本年各期比</el-radio>
    </el-radio-group>
    <!-- 月份统计 -->
    <FilterTable
      ref="bottomTable"
      height="74px"
      :fetchapi="bottomApi"
      :params="bottomFetchParams"
      :isSelectColumn="false"
      :isToperInfo="false"
      :isColumnFilter="false"
      :columns="bottomColumns"
      columnsRef="partPartPurchasePurchaseOrderCreateBatchPartSelect1"
      :isPagination="false"
      :onColumnsChange="columns => (this.bottomColumns = columns)"
    ></FilterTable>

    <div class="btnWrap">
      <el-button @click="handleCancle">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>

    <!-- 替换件查看弹窗 -->
    <BaseDialog :visible.sync="replacePartVisible" title="查看替换件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <replaceAndInventory :partInfo="visibleReplacePartInfo"></replaceAndInventory>
    </BaseDialog>
  </div>
</template>

<script>
import { queryBatchOrderPartList, queryPartMonthReport } from '@/api/part/partPurchase/purchaseOrder';

import { dictionary } from '@/utils/dictMixin';
import { formatdate, notifyAction } from '@/utils';
import replaceAndInventory from '@/pages/part/report/replaceAndInventory';

export default {
  components: {
    replaceAndInventory
  },
  mixins: [dictionary],
  props: {
    orderNo: {
      type: String,
      default: ''
    },
    dialogStatus: String
  },
  data() {
    return {
      topFilterList: this.createTopFilter(),
      tableColumns1: this.cteateTableColums1(),
      bottomColumns: this.createBottomColumns(),
      fetchapi: queryBatchOrderPartList,
      fetchParams: { xhrAbort: true },
      bottomApi: queryPartMonthReport,
      bottomFetchParams: { xhrAbort: true },
      yearFilterType: '1', // 下方筛选条件
      selectedTableData: [],
      queryInfoPart: {}, // 查询年年化信息的配件信息
      dataSource: [],
      noCountPart: 0, // 计划数量为0的配件
      tableData: [], // tbale数据
      isMiniScreen: false, // 是否是小屏幕
      screnHeight: 0, // 屏幕高度
      tableMaxHeiht: 0, // table最大高度
      visibleReplacePartInfo: {},
      replacePartVisible: false
    };
  },
  computed: {
    isFullScreen() {
      return this.dialogStatus == 'fullscreen';
    }
  },
  watch: {
    yearFilterType(newVal, oldVal) {
      if (this.queryInfoPart.partNo) {
        this.handlePartEnterEvent();
      }
    },
    isFullScreen(newVal) {
      console.log(newVal, '弹窗是否是全屏');
    },
    screnHeight(newVal) {
      this.tableMaxHeiht = newVal - (56 + 10 + 88 + 17 + 74 + 5 + 53 + 53 + 58);
      console.log(this.tableMaxHeiht, 'table最大高度');
    }
  },
  mounted() {
    console.log(window.innerHeight, '屏幕高度');
    this.screnHeight = window.innerHeight;
    this.isMiniScreen = window.innerHeight < 900;
  },
  methods: {
    createTopFilter() {
      return [
        {
          type: 'CHECKBOX',
          label: '按出库日期查询',
          fieldName: 'check',
          initialValue: 0,
          options: {
            trueValue: 1,
            falseValue: 0
          },
          change: e => {
            if (e == 1) {
              let date = new Date();
              let thisYear = date.getFullYear();
              let thisMonth = date.getMonth() + 1;
              let monthFirstDay = new Date(thisYear + '-' + thisMonth + '-1');
              this.topFilterList.find(item => item.fieldName == 'stockDateBefore|stockDateAfter').initialValue = [formatdate(monthFirstDay, 1), formatdate(new Date(), 1)];
              this.topFilterList.find(item => item.fieldName == 'stockDateBefore|stockDateAfter').disabled = false;
            } else {
              this.topFilterList.find(item => item.fieldName == 'stockDateBefore|stockDateAfter').initialValue = [];
              this.topFilterList.find(item => item.fieldName == 'stockDateBefore|stockDateAfter').disabled = true;
            }
          }
        },
        {
          type: 'RANGE_DATE',
          label: '出库日期',
          disabled: true,
          // dateType: 'daterange',
          // dateFromat: 'yyyy-MM-dd',
          // initialValue: [],
          fieldName: 'stockDateBefore|stockDateAfter',
          selfCols: 2
        },
        {
          type: 'INPUT',
          fieldName: 'mainGroupNo',
          label: '主组号'
        },
        {
          type: 'INPUT',
          fieldName: 'partNo',
          label: '配件代码'
        },
        {
          type: 'INPUT',
          fieldName: 'partName',
          label: '配件说明'
        },
        {
          type: 'CHECKBOX',
          fieldName: 'zeroStock',
          label: '零库存',
          options: {
            trueValue: 1,
            falseValue: ''
          }
        }
      ];
    },
    cteateTableColums1() {
      return [
        {
          title: '操作',
          dataIndex: 'handle',
          render: params => {
            return (
              <el-button
                type="text"
                onClick={() => {
                  this.handleCheckReplacePart(params.row);
                }}
              >
                查看替换件
              </el-button>
            );
          }
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          width: 150,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input',
          sorter: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          width: 150,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input',
          sorter: true
        },
        {
          title: '配件描述',
          dataIndex: 'partDescription',
          width: 150,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input',
          sorter: true
        },
        {
          title: '不含税采购单价',
          dataIndex: 'planPrice',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          dataIndex: 'nOrderQty',
          title: '计划数量',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          min: 0,
          //   return <el-input value={params.row.nOrderQty}></el-input>;
          // editDisableRender: params => {
          // },
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: '库存数量',
          dataIndex: 'stockquantity',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: '可用数量',
          dataIndex: 'useablequantity',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: '储备高限',
          dataIndex: 'maxStock',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: '储备低限',
          dataIndex: 'minStock',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: 'R3仓库',
          dataIndex: 'mock8',
          filter: true,
          filterType: 'input',
          sorter: true
        },
        {
          title: 'R3库存数量',
          dataIndex: 'r3Count',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        // {
        //   title: '厂家配件代码',
        //   dataIndex: 'partNo'
        // },
        // {
        //   dataIndex: 'nOrderQty'
        //   title: '在途数量',
        // },
        {
          title: '包装数量',
          dataIndex: 'packageLiaght',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        // {
        //   title: '借入数量',
        //   dataIndex: 'borrowQuantity',
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          title: '入库数量',
          dataIndex: 'inQuantity',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: '出库数量',
          dataIndex: 'outQuantity',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: '含税销售单价',
          dataIndex: 'costSalesPrice',
          filter: true,
          filterType: 'number',
          sorter: true
        },
        {
          title: '计量单位',
          dataIndex: 'packageUnit',
          filter: true,
          filterType: 'input',
          render: params => {
            return <span>{this.createDictText(params.row.packageUnit, 8105)}</span>;
          },
          sorter: true
        },
        {
          title: '配件分类代码',
          dataIndex: 'partSortCode',
          render: params => {
            return <span>{this.createDictText(params.row.partSortCode, 8106)}</span>;
          },
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8106),
          sorter: true
        },
        // {
        //   title: '车型',
        //   dataIndex: 'model',
        //   filter: true,
        //   filterType: 'input',
        //   sorter: true
        // },
        {
          title: '主组号',
          dataIndex: 'mainGroupNo',
          filter: true,
          filterType: 'input',
          sorter: true
        },
        {
          title: 'ABC标识',
          dataIndex: 'abcType',
          render: params => {
            return <span>{this.createDictText(params.row.abcType, 8092)}</span>;
          },
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8092),
          sorter: true
        },
        {
          title: '最后入库日期',
          dataIndex: 'lastStockIn',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range',
          sorter: true
        },
        {
          title: '最后出库日期',
          dataIndex: 'lastStockOut',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range',
          sorter: true
        },
        {
          title: '仅辖区发货',
          dataIndex: 'shipMark',
          filter: true,
          filterType: 'input',
          sorter: true
        }
      ];
    },
    createBottomColumns() {
      return [
        {
          title: '一月',
          dataIndex: 'outQuantity1'
        },
        {
          title: '二月',
          dataIndex: 'outQuantity2'
        },
        {
          title: '三月',
          dataIndex: 'outQuantity3'
        },
        {
          title: '四月',
          dataIndex: 'outQuantity4'
        },
        {
          title: '五月',
          dataIndex: 'outQuantity5'
        },
        {
          title: '六月',
          dataIndex: 'outQuantity6'
        },
        {
          title: '七月',
          dataIndex: 'outQuantity7'
        },
        {
          title: '八月',
          dataIndex: 'outQuantity8'
        },
        {
          title: '九月',
          dataIndex: 'outQuantity9'
        },
        {
          title: '十月',
          dataIndex: 'outQuantity10'
        },
        {
          title: '十一月',
          dataIndex: 'outQuantity11'
        },
        {
          title: '十二月',
          dataIndex: 'outQuantity12'
        }
      ];
    },
    // table数据变化(获取table数据)
    handleTableDataChange(row) {
      row.map(item => {
        item.nOrderQty = item.nOrderQty || item.planCount || 0;
      });
      let noOtyCount = 0;
      row.map(item => {
        if (item.nOrderQty != 0) {
          noOtyCount++;
        }
      });
      this.noCountPart = noOtyCount; // 统计订购数量不为0的数量
      this.tableData = row;
    },
    // 列表行项选择变化
    handleTableSelect(e) {
      this.selectedTableData = e;
      if (e.length) {
        this.handlePartEnterEvent(e[0]);
      }
    },
    // 配件单击或者双击
    handlePartEnterEvent(e) {
      this.bottomFetchParams.xhrAbort = true;
      let yearInfo = this.queryYearInfo();
      this.queryInfoPart = e || this.queryInfoPart;
      this.bottomFetchParams = Object.assign(this.bottomFetchParams, {
        xhrAbort: false,
        reportYear: this.yearFilterType == 1 ? yearInfo.lastYear : yearInfo.thisYear,
        partNo: this.queryInfoPart.partNo
      });
    },
    // 搜索条件变化
    async handleFilterChange(e) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, {
        ...e,
        orderNo: this.orderNo,
        xhrAbort: false,
        stockDateBefore: e.stockDateBefore ? e.stockDateBefore.split(' ')[0] + ' 00:00::00' : '',
        stockDateAfter: e.stockDateAfter ? e.stockDateAfter.split(' ')[0] + ' 23:59:59' : '',
        maxStock: '',
        minStock: ''
      });

      this.$refs.topTable.START_LOADING();
      let res = {};
      try {
        res = await queryBatchOrderPartList(this.fetchParams);
      } catch (error) {
        this.$refs.topTable.STOP_LOADING();
      }
      this.$refs.topTable.STOP_LOADING();
      if (res.resultCode == 200) {
        this.dataSource = res.data;
      }
    },
    // 点击按高储生成
    async hadnleHighStock() {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, {
        xhrAbort: false,
        maxStock: 1,
        minStock: ''
      });

      this.$refs.topTable.START_LOADING();
      let res = await queryBatchOrderPartList(this.fetchParams);
      this.$refs.topTable.STOP_LOADING();
      if (res.resultCode == 200) {
        this.dataSource = res.data;
      }
    },
    // 点击按低储生成
    async handleLowStock() {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, {
        xhrAbort: false,
        maxStock: '',
        minStock: 1
      });

      this.$refs.topTable.START_LOADING();
      let res = await queryBatchOrderPartList(this.fetchParams);
      this.$refs.topTable.STOP_LOADING();
      if (res.resultCode == 200) {
        this.dataSource = res.data;
      }
    },
    // 发挥当前年份跟上年年份
    queryYearInfo() {
      let date = new Date();
      return {
        thisYear: date.getFullYear(),
        lastYear: date.getFullYear() - 1
      };
    },
    handleConfirm() {
      let arr = this.tableData.filter(item => item.nOrderQty != 0);
      if (arr.length) {
        arr.map(item => {
          item.stockQuantity = item.stockquantity;
          item.useableQuantity = item.useablequantity;
        });
        this.$emit('onConfirm', arr);
        this.handleCancle();
      } else {
        notifyAction('请修改需要添加配件的计划数量', 'warning');
      }
      // if (this.selectedTableData.length) {
      //   this.selectedTableData.map(item => {
      //     item.stockQuantity = item.stockquantity;
      //     item.useableQuantity = item.useablequantity;
      //   });
      //   this.$emit('onConfirm', this.selectedTableData);
      //   this.handleCancle();
      // } else {
      //   notifyAction('请选择需要添加的配件', 'warning');
      // }
    },
    handleCancle() {
      this.$emit('close');
    },
    // 点击查看替代件
    handleCheckReplacePart(row) {
      this.visibleReplacePartInfo = row;
      this.replacePartVisible = true;
    }
  }
};
</script>

<style scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
